package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class HttpServleResponse
{
    private Socket socket;
    private File contentFile;
    private int statusCode = 200;//状态代码
    private String statusReason = "OK";//状态描述
    public  HttpServleResponse (Socket socket){
        this.socket=socket;
    }
    /*
    * 发送响应
    * 将当前响应对象内容按照标准响应格式发送到客户端
    *
    * */
    private  void  sendStatusLine() throws IOException {
        String line=" HTTP/1.1"+" "+statusCode+" "+statusReason;
        printlin(line);
    }
    private void sendHeaders() throws IOException {
        String line="Content-Type: text/html";
        printlin(line);
        line="Content-Length: "+contentFile.length();
        printlin(line);
        printlin("");
    }
    private void sendContent() throws IOException {
        OutputStream oup=socket.getOutputStream();
        FileInputStream ins=new FileInputStream(contentFile);
        byte[] datee=new byte[1024*10];
        int len;
        while ((len=ins.read(datee))!=-1){
            oup.write(datee,0,len);
        }
    }
    public  void  response() throws IOException {
        //请求头
        sendStatusLine();
        //发送响应同
        sendHeaders();
        //发送响应正文
        sendContent();
    }
    private  void  printlin(String line) throws IOException {
        OutputStream oup=socket.getOutputStream();
        byte[] data=line.getBytes(StandardCharsets.ISO_8859_1);
        oup.write(data);
        oup.write(13);
        oup.write(10);
    }
    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }
}
